package com.yangye.niodemo.rpc.proxy;

import com.yangye.niodemo.rpc.protocol.RpcBody;
import com.yangye.niodemo.rpc.transport.ClientFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.CompletableFuture;

/**
 * @author yangye
 * @date 2020/12/29
 */
public class RpcProxy {

	public static <T> T proxyGet(Class<T> clazz) {
		ClassLoader classLoader = clazz.getClassLoader();
		InvocationHandler invocationHandler = (proxy, method, args) -> {
			String name = clazz.getName();
			String methodName = method.getName();
			Class<?>[] parameterTypes = method.getParameterTypes();

			// 构建请求体
			RpcBody body = new RpcBody();
			body.setArgs(args);
			body.setMethodName(methodName);
			body.setName(name);
			body.setParameterTypes(parameterTypes);

			// 获取netty client
			CompletableFuture resFuture = ClientFactory.transport(body);
			return resFuture.get();
		};
		return (T) Proxy.newProxyInstance(classLoader, new Class[]{clazz}, invocationHandler);
	}

}
